<?php
/**
 * 关注用户
 * 新增关注记录
 * update: [lx][2019-01-29]
 */
require_once dirname(dirname(__DIR__)) . "/common.php";

use app\cls\tom\Response;
use app\cls\tom\SysResource;
use app\model\UserFollow;
use app\cls\tom\Tools;
use app\cls\tom\Process;

// 最多开启5个进程
$process = new Process(__FILE__);
$process->setProcessNum(5);
$process->initProcess();

//实例化数据库
$db = SysResource::getDB(true);
$UserFollow = new UserFollow($db);
$UserFollow->setDb($db);
$redis = SysResource::getRedis();

try {
    $index = 0;
    $runTimes = 200;
    while (true) {
        $index++;
        if ($index > $runTimes) {
            $time = date('Y-m-d H:i:s');
            echo "[{$time}] 干完活了{$runTimes}次，退出!\n";
            break;
        }

        for ($i = 1; $i <= 5; $i++) {
            for ($j = 1; $j <= 100; $j++) {
                $key = REDIS_PREFIX . "follow_" . $i;
                //从队列中弹出一个值
                $res = $redis->rPop($key);
                $data = json_decode($res, true);

                if (!empty($data)) {
                    $time = date('Y-m-d H:i:s');
                    echo "[{$time}]\n[关注]缓存数据：{$res}\n";

                    //先去数据库查询关注了这个人，关注就不在关注了
                    $db->select("id");
                    $db->from("material_follow");
                    $db->where(['my_uuid' => $data['my_uuid'], 'other_uuid' => $data['other_uuid']]);
                    $query = $db->get();
                    $row = $query->one();
                    if (!$row) {
                        // 新增关注
                        $data['add_time'] = date("Y-m-d H:i:s", time());
                        $db->insert("material_follow", $data);
                        $userId = $db->insert_id();
                        echo "[关注]新增流水[$userId]:" . $db->last_query() . "\n";
                    }
                } else {
                    continue;
                }
            }
            sleep(1);
        }
        sleep(1);
    }
} catch (Exception $e) {
    $process->log($e->getMessage());
}
